

package com.maoshi.shop.platform.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maoshi.shop.bean.bo.PayInfoBo;
import com.maoshi.shop.bean.enums.OrderStatus;
import com.maoshi.shop.common.enums.PayType;
import com.maoshi.shop.bean.model.Order;
import com.maoshi.shop.bean.model.OrderItem;
import com.maoshi.shop.bean.model.OrderSettlement;
import com.maoshi.shop.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;


@Component("orderTask")
public class OrderTask {


    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private PayService payService;
    @Autowired
    private OrderSettlementService orderSettlementService;
    @Autowired
    private PayManagerService payManagerService;


    public void cancelOrder(){
        Date now = new Date();
        logger.info("取消超时未支付订单。。。");
        // 获取30分钟之前未支付的订单
        List<Order> orders = orderService.listUnRefundOrderAndOrderItems(OrderStatus.UNPAY.value(),DateUtil.offsetMinute(now, -30));
        if (CollectionUtil.isEmpty(orders)) {
            return;
        }

        List<Order>  cancelOrderList = this.chackOrders(orders);
        orderService.cancelOrders(cancelOrderList);
        // 移除缓存
        this.removeCache(cancelOrderList);

    }

    /**
     * 确认收货
     */
    public void confirmOrder(){
        Date now = new Date();
        logger.info("系统自动确认收货订单。。。");
        // 获取15天之前等待确认收货的订单
        List<Order> orders = orderService.listUnRefundOrderAndOrderItems(OrderStatus.CONSIGNMENT.value(),DateUtil.offsetDay(now, -15));
        if (CollectionUtil.isEmpty(orders)) {
            return;
        }
        orderService.receiptOrder(orders);
        // 移除缓存
        this.removeCache(orders);
    }

    /**
     * 查询订单，去除已支付的订单
     * @param orders
     */
    private List<Order> chackOrders(List<Order> orders){
        List<String> orderNumbers=orders.stream().map(Order::getOrderNumber).collect(Collectors.toList());
        // 收集未支付的订单
        List<Order> orderList = new ArrayList<>();
        //获取订单对应的订单结算数据
        List<OrderSettlement> orderSettlementList = orderSettlementService.list(new LambdaQueryWrapper<OrderSettlement>()
                .in(OrderSettlement::getOrderNumber, orderNumbers));
        Map<String, OrderSettlement> orderSettlementMap = orderSettlementList.stream()
                .collect(Collectors.toMap(OrderSettlement::getOrderNumber, orderSettlement -> orderSettlement));
        for (Order order : orders) {
            OrderSettlement orderSettlement = orderSettlementMap.get(order.getOrderNumber());
            PayInfoBo payInfo = payManagerService.getPayInfo(PayType.instance(orderSettlement.getPayType()), orderSettlement.getPayNo());
            if(payInfo.getIsPaySuccess()){
                // 根据内部订单号更新order settlement
                List<Order> successOrderList = payService.paySuccess(payInfo.getPayNo(), payInfo.getBizPayNo());
                // 移除缓存
               this.removeCache(successOrderList);
            }else {
                orderList.add(order);
            }
        }
        return orderList;
    }

    /**
     * 移除缓存
     */
    private void removeCache(List<Order> orders){
        for (Order order : orders) {
            List<OrderItem> orderItems = order.getOrderItems();
            for (OrderItem orderItem : orderItems) {
                productService.removeProductCacheByProdId(orderItem.getProdId());
                skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
            }
        }
    }
}
